package com.example.votingsystem.service;

import com.example.votingsystem.entity.Announcement;
import com.example.votingsystem.repository.AnnouncementRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class AnnouncementService {

    @Autowired
    private AnnouncementRepository announcementRepository;

    public List<Announcement> getAllActiveAnnouncements() {
        return announcementRepository.findByIsActiveTrueOrderByCreatedAtDesc();
    }

    public List<Announcement> getAnnouncementsByCategory(String category) {
        return announcementRepository.findByIsActiveTrueAndCategoryOrderByCreatedAtDesc(category);
    }

    public Announcement getAnnouncementById(Long id) {
        return announcementRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("Announcement not found"));
    }

    public Announcement createAnnouncement(Announcement announcement) {
        return announcementRepository.save(announcement);
    }

    public Announcement updateAnnouncement(Announcement announcement) {
        if (!announcementRepository.existsById(announcement.getId())) {
            throw new RuntimeException("Announcement not found");
        }
        return announcementRepository.save(announcement);
    }
}
